﻿using System;
using System.Diagnostics;
using Gumini.JulaDB.Provider;
using Gumini.JulaDB.Test.Common;
using RandomNameGenerator;

namespace Gumini.JulaDB.DatabaseGenerator
{
    class Program
    {
        private static JulaDbConnection _connection;
        private static CustomerOrderTestDataCreator _creator;

        private static JulaDbConnection CreateFileDatabase(string filename)
        {
            var connection = new JulaDbConnection(String.Format("Data Source={0}", filename));
            connection.Open();
            return connection;
        }

        private static void GenerateCustomers(JulaDbConnection connection, int numberOfRecords)
        {
            var w = new Stopwatch();
            w.Start();

            var generator = new PersonNameGenerator();
            for (int i = 0; i < numberOfRecords; i++)
            {
                var name = generator.GenerateRandomFirstAndLastName();
                _creator.AddCustomer(name);

                const int PrintStep = 10000;
                if (i % PrintStep == 0)
                {
                    var span = w.Elapsed;
                    double percentageProgress = (double)i / (double)numberOfRecords * 100.0;
                    Console.WriteLine("{0}: {1}%, added {2}", span, percentageProgress, name);
                }
            }
        }

        private static void GenerateOrders(JulaDbConnection connection, int numberOfOrders, int numberOfCustomers)
        {
            var w = new Stopwatch();
            w.Start();

            var random = new Random();
            for (int i = 0; i < numberOfOrders; i++)
            {
                int customerId = random.Next(numberOfCustomers);
                _creator.AddOrder(customerId);

                const int PrintStep = 10000;
                if (i % PrintStep == 0)
                {
                    var span = w.Elapsed;
                    double percentageProgress = (double)i / (double)numberOfOrders * 100.0;
                    Console.WriteLine("{0}: {1}%", span, percentageProgress);
                }
            }
        }

        static void Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.WriteLine("Usage: Gumini.JulaDB.DatabaseGenerator.exe [file path] [number of customers] [number of orders]");
                return;
            }

            string path = args[0];
            int numberOfCustomers = int.Parse(args[1]);
            int numberOfOrders = int.Parse(args[2]);

            _connection = CreateFileDatabase(path);
            _creator = new CustomerOrderTestDataCreator(_connection, createSampleData: false);

            GenerateCustomers(_connection, numberOfCustomers);
            GenerateOrders(_connection, numberOfOrders, numberOfCustomers);

            _connection.Close();
        }
    }
}
